<?php
require_once("include/lsamp_curl.php");
define('EMPTY_USERNAME', 'Username was not provided!');
define('EMPTY_EMAIL', 'Email was not provided!');
define('EMPTY_PASSWORD', 'Password was not provided!');
define('EMPTY_SUBDOMAIN', 'Subdomain was not provided!');
define('CHANGED_FORMAT', 'The page format was changed!');
define('DTDNS_ADD_SUCCESS', 'Your new hostname has been added to the system');
define('NO_HOSTS_AVAILABLE', 'You already have the maximum number of Dynamic DNS hosts');
switch($_POST['provider']){
	case 'dtdns':{
			if(isset($_POST['dtdns_subdom'])){
			if(!isset($_POST['username']) || $_POST['username']=='' ){
				header('Location: create_dtdns.php?error=' . urlencode(EMPTY_USERNAME));
				exit;
			}
			if(!isset($_POST['password']) || $_POST['password']=='' ){
				header('Location: create_dtdns.php?error=' . urlencode(EMPTY_PASSWORD));
				exit;
			}
			if(!isset($_POST['dtdns_subdom']) || $_POST['dtdns_subdom']=='' ){
				header('Location: create_dtdns.php?error=' . urlencode(EMPTY_SUBDOMAIN));
				exit;
			}
			// cookie file
			$cookie_file = $_POST['username'] . '_dtdns_cookie.txt';
			if(file_exists($cookie_file)){
				unlink($cookie_file);
			}

			// create http_client
			$http_client = new lsamp_cURL(TRUE, $cookie_file, 'gzip', '', '', 60);
			// First login
			$login_url = 'https://www.dtdns.com/index.cfm?fuseaction=account.loginprocess';
			$login_data = 'username=' . $_POST['username']
						. '&password=' . $_POST['password'];
			$result = $http_client->post($login_url, $login_data, $errno, $error);
			if($errno !== 0){
				header('Location: create_dtndns.php?error=' . urlencode($error));
				exit;
			}else{
				if(preg_match('#<p class="error">((?:.(?!</p>))+)#', $result, $matches)){
					// there is an error occurred, report it
					header('Location: create_dtdns.php?error=' . urlencode($matches[1]));
					exit;
				}
			}
			$mysubdoms = explode("\r\n", $_POST['dtdns_subdom']);
			$error_msgs = array();
			$success_msgs = array();
			foreach($mysubdoms as $mysubdom){
				$mysubdom = trim($mysubdom);
				$error_msg = '';
				$success_msg = '';
				if($mysubdom == '') continue;
				// add the sub domain
				$add_action = 'https://www.dtdns.com/index.cfm?fuseaction=hosts.add_process';
				$add_post_data = 'hostname=' . $mysubdom
								. '&domain=' . $_POST['dtdns_domain'];
				$result = $http_client->post($add_action, $add_post_data, $errno, $error);
				if($errno !== 0){
					$error_msg .= $mysubdom . ": " . $error . "<br>";
				}else{
					if(preg_match('#<p class="error">((?:.(?!</p>))+)#', $result, $matches)){
						if($matches[1] != DTDNS_ADD_SUCCESS){
							// there is an error occurred, report it
							$error_msg .= $mysubdom . ": " . $matches[1] . "<br>";
						}else{
							$success_msg .= $mysubdom . ": " . "The subdomain: " . $mysubdom . " was created.<br>";
							// ok now, update the domain with the provided id
							if(!preg_match('/id=(\d+)">' . $mysubdom . '<\/a>/', $result, $matches)){
								$error_message .= $mysubdom . ": " . "Can't update ip, " . CHANGED_FORMAT . "<br>";
							}else{
								$subdom_id = $matches[1];
								$wildcard = (($_POST['dtdns_wildcard'] == true)? 1: 0);
								$update_action = 'https://www.dtdns.com/index.cfm?fuseaction=hosts.manageupdate';
								$update_post_data = 'id=' . $subdom_id
													.'&ip=' . $_POST['dtdns_ipaddr']
													.'&wildcard=' . $wildcard;
								$result = $http_client->post($update_action, $update_post_data, $errno, $error);
								if($errno !== 0){
									$error_message .= $mysubdom . ": " . "Can't update ip, " . $error . "<br>";
								}else{
									if($_POST['dtdns_ipaddr'] != '') $success_msg .= $mysubdom . ": " . "And its ip is now updated to " . $_POST['dtdns_ipaddr'] . "<br>";
									else
										$success_msg .= $mysubdom . ": " . "And its ip is this web server ip.<br>" ;
								}
							}
						}
					}
				}

				if($error_msg !== '')array_push($error_msgs, $error_msg);
				if($success_msg !== '')array_push($success_msgs, $success_msg);
				sleep(3);
			}
			if(count($success_msgs)>0)$success_message = implode("---<br>", $success_msgs);
			if(count($error_msgs)>0)$error_message = implode("---<br>", $error_msgs);
			header('Location: create_dtdns.php?success=' . urlencode($success_message) . "&error=" . urlencode($error_message));
		}
	}
	break;
	/* -- DynDNS.com --*/
	case 'dyndns':{
		if(isset($_POST['dyndns_subdom'])){
			if(!isset($_POST['username']) || $_POST['username']=='' ){
				header('Location: create_dyndns.php?error=' . urlencode(EMPTY_USERNAME));
				exit;
			}
			if(!isset($_POST['password']) || $_POST['password']=='' ){
				header('Location: create_dyndns.php?error=' . urlencode(EMPTY_PASSWORD));
				exit;
			}
			if(!isset($_POST['dyndns_subdom']) || $_POST['dyndns_subdom']=='' ){
				header('Location: create_dyndns.php?error=' . urlencode(EMPTY_SUBDOMAIN));
				exit;
			}
			/*$_POST['username'] = 'lsampgroup';
			$_POST['password'] = 'lsamp2010';
			$_POST['dyndns_domain'] = 'dyndns.org';
			$_POST['dyndns_subdom'] = 'lsamp';
			$_POST['dyndns_ipaddr'] = '192.168.2.123';*/
			// initialize the http client
			$cookie_file = $_POST['username'] . '_dyndns_cookie.txt';
			if(file_exists($cookie_file)){
				unlink($cookie_file);
			}
			$http_client = new lsamp_cURL(TRUE, $cookie_file, 'gzip', '', 'https://www.dyndns.com/account/services/hosts/add.html', 60);
			// login the site
			$login_url = 'https://www.dyndns.com/account/';
			$login_data = '__login=1'
						. '&username=' . $_POST['username']
						. '&password=' . $_POST['password'];

			$result = $http_client->post($login_url, $login_data, $errno, $error);
			if($errno !== 0){
				header('Location: create_dyndns.php?error=' . urlencode($error));
				exit;
			}else{
				if(preg_match('#<p class="error">((?:.(?!</p>))+)#', $result, $matches)){
					// there is an error occurred, report it
					header('Location: create_dyndns.php?error=' . urlencode($matches[1]));
					exit;
				}
			}
			$mysubdoms = explode("\r\n", $_POST['dyndns_subdom']);
			$error_msgs = array();
			$success_msgs = array();
			foreach($mysubdoms as $mysubdom){
				$mysubdom = trim($mysubdom);
				$error_msg = '';
				$success_msg = '';
				if($mysubdom == '') continue;
				// Create the subdomain
				$wildcard = (($_POST['dyndns_wildcard'] == true)? 'Y': 'N');
				$add_action = 'https://dyndns.com/account/services/hosts/add.html';
				$result = $http_client->get($add_action, $errno, $error);
				if($errno !== 0){
					$error_msg .= $error;
				}else{
					$no_hosts = NO_HOSTS_AVAILABLE;
					if(strstr($result, $no_hosts)){
						$error_msg .= $mysubdom .": ". NO_HOSTS_AVAILABLE . "<br>";
					}else{
						if(!preg_match('/<input type=\'hidden\' name=\'multiform\' value=\'([^\']+)\'/', $result, $matches)){
							$error_msg .= $mysubdom .": ". CHANGED_FORMAT . "<br>";
						}else{
							$multiform = $matches[1];
							$add_post_data ="host=" . $mysubdom
									. "&domain=" . $_POST['dyndns_domain']
									. "&service=IP"
									. "&cur_ip=" . $_POST['dyndns_ipaddr']
									. "&ttl=60"
									. "&redir_to="
									. "&cloak_title="
									. "&wildcard=" . $wildcard
									. "&mx=&"
									. "backmx=N"
									. "&submit=Create+Host"
									. "&multiform=" . $multiform;
							//$result = $http_client->post($add_action, $add_post_data, $errno, $error);
							$header[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
							$header[] = 'Connection: Keep-Alive';
							$header[] = 'Keep-Alive: 300';
							$header[] = 'Content-type: application/x-www-form-urlencoded';
							$header[] = 'Referer: https://www.dyndns.com/account/services/hosts/add.html ';
							$user_agent ='Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.4, Ant.com Toolbar 1.1';
							$url = 'https://www.dyndns.com/account/services/hosts/add.html';
							$timeout = 60;
							$compression ='gzip';
							$process = curl_init();
							curl_setopt($process, CURLOPT_URL, $url);
							curl_setopt($process, CURLOPT_HTTPHEADER, $header);
							curl_setopt($process, CURLOPT_HEADER, 1);
							curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
							//curl_setopt($process, CURLOPT_COOKIESESSION, TRUE);
							curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);
							curl_setopt($process, CURLOPT_COOKIEFILE, $cookie_file);
							curl_setopt($process, CURLOPT_COOKIEJAR, $cookie_file);
							curl_setopt($process, CURLOPT_ENCODING , $compression);
							curl_setopt($process, CURLOPT_TIMEOUT, $timeout);
							curl_setopt($process, CURLOPT_VERBOSE, 1);
							curl_setopt($process, CURLOPT_POSTFIELDS, $add_post_data);
							curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
							curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
							curl_setopt($process, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
							curl_setopt($process, CURLOPT_POST, 1);
							$result = curl_exec($process);
							$errno = 0;
							$error = '';
							if(($errno = curl_errno($process)) != 0){
								$error = curl_error($process);
							}
							if($errno !== 0){
								$error_msg .= $mysubdom .": ". $error;
								continue;
							}else{
								if(preg_match_all('/<p class=\'error\'([^>]+)>([^<]+)<\/p>/m', $result, $matches)){
									for($i = 0; $i <count($matches[2]); $i++){
										$error_msg .= $mysubdom .": ". $matches[2][$i] . "<br>";
									}
								}else{
									$subdom = $mysubdom . "." . $_POST['dyndns_domain'];
									if(strstr($result, "Hostname " . $subdom  ." created.")){
										$success_msg = $mysubdom .": " . 'The sub-domain: ' . $subdom . ' is created with ip: ' . $_POST['dyndns_ipaddr'] . "<br>";
									}else{
										$error_msg .= $mysubdom .": ". CHANGED_FORMAT . "<br>";
									}
								}
							}
						}
					}
				}
				if($error_msg !== '')array_push($error_msgs, $error_msg);
				if($success_msg !== '')array_push($success_msgs, $success_msg);
				sleep(3);
			}
			if(count($success_msgs)>0)$success_message = implode("---<br>", $success_msgs);
			if(count($error_msgs)>0)$error_message = implode("---<br>", $error_msgs);
			header('Location: create_dyndns.php?success=' . urlencode($success_message) . "&error=" . urlencode($error_message));

		}
	}
	break;
	/* -- EditDNS.net --*/
	case 'editdns':{
			/* checking input parameters */
			if((!isset($_POST['username'])) || $_POST['username']=='' ){
				header('Location: create_editdns.php?error=' . urlencode(EMPTY_EMAIL));
				exit;
			}
			if((!isset($_POST['password'])) || $_POST['password']=='' ){
				header('Location: create_editdns.php?error=' . urlencode(EMPTY_PASSWORD));
				exit;
			}
			if((!isset($_POST['editdns_subdom'])) || $_POST['editdns_subdom']=='' ){
				header('Location: create_editdns.php?error=' . urlencode(EMPTY_SUBDOMAIN));
				exit;
			}

			// cookie file
			$cookie_file = $_POST['username'] . '_editdns_cookie.txt';
			if(file_exists($cookie_file)){
				unlink($cookie_file);
			}

			// create http_client
			$http_client = new lsamp_cURL(TRUE, $cookie_file, 'gzip', '', '', 60);

			// login the site
			$login_url = "https://www.editdns.net/index.php";
			$login_data = "site=login&email=" . $_POST['username']
						. "&password=" . $_POST['password']
						. "&login=Login";
			$result = $http_client->post($login_url, $login_data, $errno, $error);
			if($errno !== 0){
				header('Location: create_editdns.php?error=' . urlencode($error));
				exit;
			}else{
				if(preg_match('#<td class="warning"><font color="red"><b>((?:.(?!</b>))+)#', $result, $matches)){
					// there is an error occurred, report it
					header('Location: create_editdns.php?error=' . urlencode($matches[1]));
					exit;
				}
			}

			// add each of subdomains to the editdns site
			$mysubdoms = explode("\r\n", $_POST['editdns_subdom']);
			$error_msgs = array();
			$success_msgs = array();

			$dynamic_domains = array( // need reviewing
				'9931' => 'mydyn.net',
				'6289' => 'resolveme.com'
			);

			// create each subdomain
			foreach($mysubdoms as $mysubdom){
				$mysubdom = trim($mysubdom);
				$error_msg = '';
				$success_msg = '';
				if($mysubdom == '') continue;
				// add the sub domain
				$add_action = "http://www.editdns.net/index.php";
				$add_post_data= "site=main"
							. "&domainType=subdomain"
							. "&domain1="
							. "&defaultIP="
							. "&domain2="
							. "&masterIP="
							. "&domain3=" . $mysubdom
							. "&dynamic=" . $_POST['editdns_domain']
							. "&addDomains=Add+Domain%28s%29";
				$result = $http_client->post($add_action, $add_post_data, $errno, $error);
				if($errno !== 0){
					$error_msg .= $mysubdom . ": " . $error . "<br>";
				}else{
					// checking return error
					if(preg_match('#<td class="warning"><font color="red"><b>((?:.(?!</b>))+)#', $result, $matches)){
						// there is an error occurred, report it
						$error_msg .= $mysubdom .": " . $matches[1] . "<br>";
					}else{
						// the subdomain is created. Now, update the domain with the provided id
						$full_subdom = $mysubdom . "." . $dynamic_domains[$_POST['editdns_domain']]; // full sub-domain
						$success_msg .= $mysubdom . ": " . "The subdomain: " . $full_subdom . " was created.<br>";

						$id_pattern = '#<td>' . str_replace(".", "\.", $full_subdom ). '</td><td><center><a href="http://www\.editdns\.net/\?site=modify-sub&modify=1&zone=(\d+)&szone=(\d+)">#m'; // build pattern to extract zone and szone value
						if(!preg_match( $id_pattern, $result, $matches)){
							$error_msg .= $mysubdom . ": " . "Can not update ip, " . CHANGED_FORMAT . "<br>";
						}else{
							$zone = $matches[1]; // zone
							$szone = $matches[2]; // szone
							// fetch the edit page and get the field_no 1, editme 3 hidden value.
							$result = $http_client->get('https://www.editdns.net/?site=modify-sub&modify=1&zone=' . $zone . '&szone=' . $szone, $errno, $error);
							if($errno !== 0){
								$error_msg .= $mysubdom . ": " . $error . "<br>";
							}else{
								// get q_data
								$q_data_pattern = '#<td field_no=\'1\' editme=\'3\'><input type=\'hidden\' value=\'(\d+)\'><\/td>#';
								if(!preg_match( $q_data_pattern, $result, $matches)){
									$error_msg .= $mysubdom . ": " . "Can not get q_data, " . CHANGED_FORMAT . "<br>";
								}else{
									$q_data = $matches[1];
									// update the ip
									$update_action = 'https://www.editdns.net/xmlhttp/xmlhttp.row.put.php';
									$update_post_data = 'cmd=row-save'
														. '&szone=' . $szone
														. '&q_data=' . $q_data
														. '|^|'
														. $full_subdom . '.'
														. '|^|A|^| 1|^|'
														. $_POST['editdns_ipaddr']
														. '|^|';
									$result = $http_client->post($update_action, $update_post_data, $errno, $error);
									if($errno !== 0){
										$error_msg .= $mysubdom . ": " . $error . "<br>";
									}else{
										//extract error_data
										$error_data_pattern = '#<error_data>(.*)<\/error_data>#';
										if(!preg_match( $error_data_pattern, $result, $matches)){
											$error_msg .= $mysubdom . ": " . "Can not get q_data, " . CHANGED_FORMAT . "<br>";
										}else{
											if($matches[1] == 'ok'){
												$success_msg .= $mysubdom . ": " . "And its ip is now updated to " . $_POST['editdns_ipaddr'] . "<br>";
											}else{
												preg_match('/\[([^\[\]]+)]/', $matches[1], $matches_l2);
												$error_msg .=  $mysubdom .": " . $matches_l2[1] . "(" . $_POST['editdns_ipaddr'] . ")<br>";
											}
										}
									}
								}
							}
						}
					}
				}
				if($error_msg !== '')array_push($error_msgs, $error_msg);
				if($success_msg !== '')array_push($success_msgs, $success_msg);
				sleep(3);
			}
			if(count($success_msgs)>0)$success_message = implode("---<br>", $success_msgs);
			if(count($error_msgs)>0)$error_message = implode("---<br>", $error_msgs);
			header('Location: create_editdns.php?success=' . urlencode($success_message) . "&error=" . urlencode($error_message));
		}
		break;
	default:
		break;
}

